package cn.dai;

import java.io.*;
import java.util.Arrays;

/**
 * @author ArkD42
 * @file 1 - Java基础语法
 * @create 2020 - 04 - 22 - 15:03
 */
public class SerializableTest {
    public static void main(String[] args) throws Exception {
        //persistence();
        activation();
    }

    // 对象持久化
    static void persistence() throws Exception {
        // 创建对象流
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("ObjectStore.txt")));

        // 写入对象
        objectOutputStream.writeObject(new Person("杰哥",24,true,new String[]{"锐普阿伟","狂笑","尾行"}));

        // 刷新
        objectOutputStream.flush();
        // 释放
        objectOutputStream.close();
    }
    // 对象活化
    static void activation() throws Exception {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("ObjectStore.txt")));
        Object object = objectInputStream.readObject();
        if (object instanceof Person) {
            Person person = (Person) object;
            System.out.println(person);
        }
        objectInputStream.close();
    }
}
// 对象要实现可序列化接口
class Person implements Serializable {

    private static final long serialVersionUID = -6849794470754667710L;

    String name;
    Integer age;
    Boolean gender;
    String[] hobby;

    public Person(String name, Integer age, Boolean gender, String[] hobby) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.hobby = hobby;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getGender() {
        return gender;
    }

    public void setGender(Boolean gender) {
        this.gender = gender;
    }

    public String[] getHobby() {
        return hobby;
    }

    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                ", hobby=" + Arrays.toString(hobby) +
                '}';
    }
}